// 1.0引入axios
import axios from 'axios'
import qs from 'qs'
import local from '../utils/locl.js'

import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 2.0设置其他信息   请求的基本路径，请求超时的时间，拦截器，请求头...
axios.defaults.baseURL = 'http://127.0.0.1:5000'
// 拦截器
axios.interceptors.request.use(config => {
  Nprogress.start()
  const token = local.get('token')
  if (token) {
    // 拦截器
    config.headers.Authorization = token
  }
  return config
})

// 响应
axios.interceptors.response.use(res => {
  Nprogress.done()
  return res
})

// 3.0封装请求码
export default {
  get(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  post(url, body) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, qs.stringify(body))
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
